package com.newdjk.newdoctor.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.Areadapter;
import com.newdjk.newdoctor.adapter.CityAdapter;
import com.newdjk.newdoctor.entity.CityEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.okhttp.entity.BaseEntity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static androidx.recyclerview.widget.OrientationHelper.VERTICAL;

public class CityChooseDialog {
    private static final String TAG = "CityChooseDialog";
    private Dialog mDialog;
    private View mView;
    private static CityChooseDialog mInstance;
    private Context mContext;
    private ArrayList<CityEntity.DataBean> mCityList = new ArrayList<>();
    private ArrayList<CityEntity.DataBean> mProvinceList = new ArrayList<>();
    private RecyclerView mRecyclerviewProvince;
    private RecyclerView mRecyclerviewCity;
    private RecyclerView mRecyclerviewArea;
    private CityAdapter mProvinceAdapter;

    private LinearLayoutManager layoutManager;
    private CityAdapter mCityAdapter;
    private List<CityEntity.DataBean> dataArea = new ArrayList<>();
    private Areadapter mAreaAdapter;
    private int areaId;
    private int mArreaid;
    private View tvSure;
    private View tvCancel;
    private CitySelectListener SelectListenerlistener;
    private static final int LOADING_SUCCESS = 2;
    Gson gson = new Gson();
    private String mProvinceName;
    private String mcityName;
    private String mAreaName;
    private String path;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOADING_SUCCESS:

                    break;
                default:
                    break;
            }
        }
    };



    public static CityChooseDialog getInstance() {
        if (mInstance == null) {
            synchronized (CityChooseDialog.class) {
                if (mInstance == null) {
                    mInstance = new CityChooseDialog();
                }
            }
        }
        return mInstance;
    }

    public void showBottomSexDialog(Context ctx, String areaId, final CitySelectListener listener) {
        SelectListenerlistener = listener;
        mView = View.inflate(ctx, R.layout.layout_bottom_city_dialog, null);
        mContext = ctx;
        mRecyclerviewProvince = mView.findViewById(R.id.mRecyclerview_province);
        mRecyclerviewCity = mView.findViewById(R.id.mRecyclerview_city);
        mRecyclerviewArea = mView.findViewById(R.id.mRecyclerview_area);
        tvCancel = mView.findViewById(R.id.tv_cancel);
        tvSure = mView.findViewById(R.id.tv_sure);
        initAreaRecycleView();
        //初始化城市列表
        initCityRecycleView();

        initProvinceRecycleView("0");

        mDialog = new Dialog(ctx, R.style.ActionSheetDialogStyle);//dialog样式
        mDialog.setContentView(mView);

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDialog.dismiss();
            }
        });


        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //DisplayMetrics d = ctx.getResources().getDisplayMetrics();
        lp.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        mDialog.show();
    }

    @SuppressLint("WrongConstant")
    private void initAreaRecycleView() {
        mAreaAdapter = new Areadapter(dataArea);
        //mRecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        mRecyclerviewArea.setAdapter(mAreaAdapter);
        mRecyclerviewArea.setLayoutManager(new LinearLayoutManager(mContext, VERTICAL, false));
        mAreaAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                CityEntity.DataBean mProvinceDataBean = dataArea.get(position);
                mAreaName = mProvinceDataBean.getAreaName();
                path=mProvinceDataBean.getPath();
                SelectListenerlistener.citySelectListener(mProvinceName, mcityName , mAreaName, path);
                if (mDialog != null) {
                    mDialog.dismiss();
                }
            }
        });

    }

    @SuppressLint("WrongConstant")
    private void initProvinceRecycleView(String areid) {
        mRecyclerviewProvince.setLayoutManager(new LinearLayoutManager(mContext, VERTICAL, false));
        mRecyclerviewProvince.setHasFixedSize(true);
        mProvinceAdapter = new CityAdapter(mProvinceList);
        mRecyclerviewProvince.setAdapter(mProvinceAdapter);
        requestCityData(areid, false);

        mProvinceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                CityEntity.DataBean mProvinceDataBean = mProvinceList.get(position);
                mProvinceName = mProvinceDataBean.getAreaName();
                requestCityData(mProvinceDataBean.getAreaId() + "", true);
            }
        });

        //获取地区


    }

    @SuppressLint("WrongConstant")
    private void initCityRecycleView() {
        mRecyclerviewCity.setLayoutManager(new LinearLayoutManager(mContext, VERTICAL, false));
        mRecyclerviewCity.setHasFixedSize(true);
        mCityAdapter = new CityAdapter(mCityList);
        mRecyclerviewCity.setAdapter(mCityAdapter);
        mCityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                // ToastUtil.setToast(mCityList.get(position).getAreaName());
                CityEntity.DataBean mcitybean = mCityList.get(position);
                if (mcitybean.getAreaName().equals(mcityName)){ //点的同一个
                    mcityName = mcitybean.getAreaName();
                    if (dataArea.size() == 0) {
                        mAreaName = "";
                        SelectListenerlistener.citySelectListener(mProvinceName , mcityName , mAreaName,path);
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                    }
                }else {
                    mcityName = mcitybean.getAreaName();
                    requestAreaData(mcitybean.getAreaId() + "");
                }

            }
        });
    }

    private void requestAreaData(String areid) {
        NetServices.Factory.getService().QueryAreaByParentId(areid + "").subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(mContext) {
                    @Override
                    public void onNext(BaseEntity entituy) {

                        LogUtils.d(TAG, entituy.getData() + "");
                        String jsonString = gson.toJson(entituy);
                        CityEntity cityEntity = gson.fromJson(jsonString, CityEntity.class);

                        //市
                        if (entituy.getCode() == 0) {
                            dataArea.clear();
                            dataArea.addAll(cityEntity.getData());
                            mAreaAdapter.setNewInstance(dataArea);
                            mAreaAdapter.notifyDataSetChanged();
                            //获取省会成功之后，再根据省会获取市
                        } else {
                            ToastUtil.setToast(entituy.getMessage());
                        }

                    }

                    @Override
                    protected void onSuccees(BaseEntity t) throws Exception {

                    }
                });

    }


    private void requestCityData(String areid, final boolean isCity) {
        NetServices.Factory.getService().QueryAreaByParentId(areid + "").subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(mContext) {
                    @Override
                    protected void onSuccees(BaseEntity entituy) throws Exception {
                        LogUtils.d(TAG, entituy.getData() + "");
                        String jsonString = gson.toJson(entituy);
                        CityEntity cityEntity = gson.fromJson(jsonString, CityEntity.class);

                        if (isCity) {
                            //市
                            if (entituy.getCode() == 0) {
                                mCityList.clear();
                                mCityList.addAll(cityEntity.getData());
                                mCityAdapter.setNewInstance(mCityList);
                                mCityAdapter.notifyDataSetChanged();
                                //获取省会成功之后，再根据省会获取市
                                mcityName = mCityList.get(0).getAreaName();
                                path = mCityList.get(0).getPath();
                                requestAreaData(mCityList.get(0).getAreaId() + "");
                            } else {
                                ToastUtil.setToast(entituy.getMessage());
                            }
                        } else {
                            //省分
                            if (entituy.getCode() == 0) {
                                mProvinceList.clear();
                                mProvinceList.addAll(cityEntity.getData());
                                mProvinceAdapter.setNewInstance(mProvinceList);
                                mProvinceAdapter.notifyDataSetChanged();
                                if (mProvinceList.size() > 0) {
                                    // 保存之前选中的省份  滑动到之前选中的省份
                                    for (int i = 0; i < mProvinceList.size(); i++) {
                                        Log.d(TAG, "areaId " + areaId + "  " + mProvinceList.get(i).getAreaId());
                                        if (mArreaid == mProvinceList.get(i).getAreaId()) {
                                            mRecyclerviewProvince.scrollToPosition(i);
                                        }
                                    }

                                    if (mArreaid != 0) {
                                        CityEntity.DataBean mProvinceDataBean = mProvinceList.get(0);
                                        mProvinceName = mProvinceDataBean.getAreaName();
                                        requestCityData(mArreaid + "", true);
                                    } else {
                                        //如果之前没有保存省份，就直接用第一个省份
                                        CityEntity.DataBean mProvinceDataBean = mProvinceList.get(0);
                                        mProvinceName = mProvinceDataBean.getAreaName();
                                        requestCityData(mProvinceDataBean.getAreaId() + "", true);
                                    }

                                }
                            } else {
                                ToastUtil.setToast(entituy.getMessage());
                            }
                        }
                    }


                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        ToastUtil.setToast(erroressage + "");

                    }
                });


    }

    public interface CitySelectListener {
        void citySelectListener(String provinceName, String cityName, String areaName, String path);
    }
}
